import uvicorn,json
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from aaa.utils import conn_mysql
app = FastAPI()

origins = [
    "http://10.10.10.75:8081"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

def get_alerts_from_db(type=None):
    sql = 'SELECT county,red_alerts,orange_alerts,yellow_alerts,blue_alerts from sf1170'
    res = conn_mysql.conn_mysql(sql)
    print('get_alerts_from_db res',res)
    for item in res:
        if ('娄底' in item[0]):
            ld = list(map(lambda i: json.loads(i), item[1:]))
            print('ld 1',ld)
        elif ('长沙' in item[0]):
            css = list(map(lambda i: json.loads(i), item[1:]))
        elif ('邵阳' in item[0]):
            sys = list(map(lambda i: json.loads(i), item[1:]))
        elif ('益阳' in item[0]):
            yys = list(map(lambda i: json.loads(i), item[1:]))
        elif ('张家界' in item[0]):
            zjjs = list(map(lambda i: json.loads(i), item[1:]))
        elif ('湘西' in item[0]):
            xxz = list(map(lambda i: json.loads(i), item[1:]))
        elif ('常德' in item[0]):
            cds = list(map(lambda i: json.loads(i), item[1:]))
        elif ('株洲' in item[0]):
            zzs = list(map(lambda i: json.loads(i), item[1:]))
    return (ld,css,sys,yys,zjjs,xxz,cds,zzs)

def get_alerts4_from_db():
    import pysnooper
    sql = 'SELECT county,red_alerts,orange_alerts,yellow_alerts,blue_alerts from sf1170'
    # sql = "SELECT county,json_extract(red_alerts,'$[*]'),json_extract(orange_alerts,'$[*]'),json_extract(yellow_alerts,'$[*]'),json_extract(blue_alerts,'$[*]') from sf1170"
    # sql = "SELECT county,json_extract(red_alerts,'$[*].point'),json_extract(red_alerts,'$[*].content'),json_extract(orange_alerts,'$[*].point'),json_extract(orange_alerts,'$[*].content'),json_extract(yellow_alerts,'$[*].point'),json_extract(yellow_alerts,'$[*].content'),json_extract(blue_alerts,'$[*].point'),json_extract(blue_alerts,'$[*].content') from sf1170"
    res = conn_mysql.conn_mysql(sql)
    print('get_alerts4_from_db res',res)
    cds_list,ld_list,sys_list,css_list,zjjs_list,zzs_list,yys_list,xxz_list = [],[],[],[],[],[],[],[]
    for k, v in enumerate(res):
        if ('常德' in res[k][0]):
            cds_list.append(res[k][0])
            for i in res[k][1:]:
                cds_list.append(json.loads(i))
        elif ('娄底' in res[k][0]):
            ld_list.append(res[k][0])
            for i in res[k][1:]:
                ld_list.append(json.loads(i))
        elif ('邵阳' in res[k][0]):
            sys_list.append(res[k][0])
            for i in res[k][1:]:
                sys_list.append(json.loads(i))
        elif ('湘西' in res[k][0]):
            xxz_list.append(res[k][0])
            for i in res[k][1:]:
                xxz_list.append(json.loads(i))
        elif ('张家界' in res[k][0]):
            zjjs_list.append(res[k][0])
            for i in res[k][1:]:
                zjjs_list.append(json.loads(i))
        elif ('株洲' in res[k][0]):
            zzs_list.append(res[k][0])
            for i in res[k][1:]:
                zzs_list.append(json.loads(i))
        elif ('益阳' in res[k][0]):
            yys_list.append(res[k][0])
            for i in res[k][1:]:
                yys_list.append(json.loads(i))
        elif ('长沙' in res[k][0]):
            css_list.append(res[k][0])
            for i in res[k][1:]:
                css_list.append(json.loads(i))
    ld = ld_list[1:]
    print('cds111')
    with pysnooper.snoop():
        cds = cds_list[1:]
        sys = sys_list[1:]
        xxz = xxz_list[1:]
        zjjs = zjjs_list[1:]
        zzs = zzs_list[1:]
        yys = yys_list[1:]
        css = css_list[1:]

    return {'cds':cds,'ld':ld,'sys':sys,'xxz':xxz,'zjjs':zjjs,'zzs':zzs,'yys':yys,'css':css}

def get_rains_from_db():
    sql = 'SELECT city,rain from rains'
    res = conn_mysql.conn_mysql(sql)
    print('get_rains_from_db res',res)
    return res

def get_rate_from_db():
    sql = 'SELECT county,rate from rate'
    res = conn_mysql.conn_mysql(sql)
    print('get_rate_from_db res',res)
    return res

@app.get('/alerts3')
def alerts3():
    res = get_alerts_from_db()
    ld, css, sys, yys, zjjs, xxz, cds, zzs = res[0], res[1], res[2], res[3], res[4], res[5], res[6], res[7]
    print('Alert3View res', ld, css)
    return JSONResponse({'data': {'ld': ld, 'css': css, 'sys': sys, 'yys': yys, 'zjjs': zjjs,
                                  'xxz': xxz, 'cds': cds, 'zzs': zzs}})

@app.get('/alerts4')
def index():
    """ 普通操作接口 """
    res = get_alerts4_from_db()
    cds, ld, sys, xxz, zjjs, zzs, yys, css = res['cds'], res['ld'], res['sys'], res['xxz'], res['zjjs'], res['zzs'], \
                                             res['yys'], res['css']
    print('Alert4View res', type(cds), cds)
    return JSONResponse(
        {'data': {'cds': cds, 'ld': ld, 'sys': sys, 'xxz': xxz, 'zjjs': zjjs, 'zzs': zzs, 'yys': yys, 'css': css}})

@app.get('/rain')
def rain():
    res = get_rains_from_db()
    # ld, css, sys, yys,zjjs,xxz,cds,zzs = res[0], res[1], res[2], res[3], res[4], res[5], res[6], res[7]
    for i in res:
        city = i[0].strip()
        print('city', city)
        # rate = i[1]
        if (city == '益阳'):
            yys = i
        elif (city == '永顺'):
            xxz = i
        elif (city == '长沙'):
            css = i
        elif (city == '张家界'):
            zjjs = i
        elif (city == '邵阳市'):
            sys = i
        elif (city == '株洲'):
            zzs = i
        elif (city == '常德'):
            cds = i
        elif (city == '娄底'):
            ld = i
    print('RainView res', ld, css)
    return JSONResponse({'data': {'ld': ld, 'css': css, 'sys': sys, 'yys': yys, 'zjjs': zjjs,
                                  'xxz': xxz, 'cds': cds, 'zzs': zzs}})

@app.get('/rate')
def rate():
    res = get_rate_from_db()
    for i in res:
        county = i[0]
        # rate = i[1]
        if (county == '益阳'):
            yys = i
        elif (county == '湘西'):
            xxz = i
        elif (county == '长沙'):
            css = i
        elif (county == '张家界'):
            zjjs = i
        elif (county == '邵阳'):
            sys = i
        elif (county == '株洲'):
            zzs = i
        elif (county == '常德'):
            cds = i
        elif (county == '娄底'):
            ld = i
    # ld, css, sys, yys,zjjs,xxz,cds,zzs = res[7], res[2], res[3], res[0], res[4], res[1], res[6], res[5]
    print('RateView res', ld, css, res)
    return JSONResponse({'data': {'ld': ld, 'css': css, 'sys': sys, 'yys': yys, 'zjjs': zjjs,
                                  'xxz': xxz, 'cds': cds, 'zzs': zzs}})

@app.get('/dx')
def get():
    sql = 'SELECT * from offline1170'
    res = conn_mysql.conn_mysql(sql)[0][2:]
    print(res)
    print('OfflineView res', res)
    return JSONResponse({'data':{'online':res}})

@app.get('/stat')
def stat():
        red = []
        orange = []
        yellow = []
        blue = []


        res2 = get_alerts_from_db()

        def get_len(item, color, num):
            if item[num]:
                color.append(len(item[num]))
            else:
                color.append('')

        for item in res2:
            print(item)
            get_len(item, red, 0)
            get_len(item, orange, 1)
            get_len(item, yellow, 2)
            get_len(item, blue, 3)
        return JSONResponse({'data': {
            'red':red,
            'orange': orange,
            'yellow': yellow,
            'blue': blue,
        }})

if __name__ == '__main__':
    uvicorn.run("fast:app",host="10.10.10.75", port=5000, log_level="info")